package com.tanhua.dubbo.api;


import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
@Slf4j
public class CommentsApiImpl implements CommentsApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 分页查询动态内的评论
     *
     * @param movementId
     * @return
     */
    @Override
    public List<Comment> find(String movementId, CommentType comment, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("publishId")
                .is(new ObjectId(movementId))
                .and("commentType")
                .is(comment.getType());
        Query query = new Query(criteria).skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments;
    }

    /**
     * 更新点赞评论喜欢到Moverment 然后返回总数
     *
     * @param commentrusult
     * @return
     */
    @Override
    public Integer save(Comment commentrusult) {
        //获取commentrusult中的被评论人ID
        Movement movement = mongoTemplate.findById(commentrusult.getPublishId(), Movement.class);
        if (movement != null) {
            commentrusult.setPublishUserId(movement.getUserId());
        }
        //保存commentrusult到数据库
        mongoTemplate.save(commentrusult);
        //保存评论+1的数据到Movement表
        Query query = new Query(Criteria.where("id").is(movement.getId()));
        Update update = new Update();
        if (commentrusult.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);
        } else if (commentrusult.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", 1);
        } else {
            update.inc("loveCount", 1);
        }

        //设置更新
        FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
        findAndModifyOptions.returnNew(true);
        //获取更新后的最新参数
        Movement andModify = mongoTemplate.findAndModify(query, update, findAndModifyOptions, Movement.class);

        return andModify.statisCount(commentrusult.getCommentType());

    }

    @Override
    public boolean hasComment(String movementId, Long userId, CommentType like) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(movementId))
                .and("commentType").is(like.getType())
                .and("userId").is(userId));
        return mongoTemplate.exists(query, Comment.class);
    }

    /**
     * 取消点赞
     *
     * @param comment
     * @return
     */
    @Override
    public Integer delete(Comment comment) {
        //查询到点赞数据
        Query query = Query.query(Criteria.where("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType())
                .and("userId").is(comment.getUserId()));
        //删除comment表里面的点赞记录
        mongoTemplate.remove(query, Comment.class);
        //movement表里面的点赞记录 -1
        Query query1 = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", -1);
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", -1);
        } else {
            update.inc("loveCount", -1);
        }

        //设置更新参数
        FindAndModifyOptions modify = new FindAndModifyOptions();
        modify.returnNew(true);

        Movement andModify = mongoTemplate.findAndModify(query1, update, modify, Movement.class);
        return andModify.statisCount(comment.getCommentType());
    }

   /* @Override
    public Integer commentslike(String id) {
        //找到comment表里面的评论id的数据 随后更新评论点赞数
        Comment comment = mongoTemplate.findById(id, Comment.class);
        log.info("comment={}",comment);
        System.out.println(comment);
        Query query = new Query(Criteria.where("_id").is(new ObjectId(id)));
        Update update = new Update();
        update.inc("likeCount",1);
        FindAndModifyOptions modify = new FindAndModifyOptions();
        modify.returnNew(true);
        Comment andModify = mongoTemplate.findAndModify(query, update, modify, comment.getClass());
        return andModify.getLikeCount();
    }*/

  /*  @Override
    public Integer commentsdislike(String id) {
        Query query = Query.query(Criteria.where("_id").is(new ObjectId(id)));
        Update update = new Update();
        update.inc("likeCount",-1);
        FindAndModifyOptions modify = new FindAndModifyOptions();
        modify.returnNew(true);
        Comment comment = mongoTemplate.findAndModify(query, update, modify, Comment.class);
        return comment.getLikeCount();
    }*/

    @Override
    public Boolean likeCount(Comment comment) {
        //查询comment表是否已经给评论点过赞
        Query query = Query.query(Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType()));
        return mongoTemplate.exists(query, comment.getClass());
    }

    @Override
    public Map<String, Comment> commentslike(Comment comment) {
        //取出评论数据里面的userid
        Comment comment1 = mongoTemplate.findById(comment.getPublishId(), Comment.class);
        //将publisuserid封装到comment里面 然后添加到comment数据库里面
        comment.setPublishUserId(comment1.getUserId());
        mongoTemplate.save(comment);
        //更新comment表，评论点赞数据+1
        Query query = new Query(Criteria.where("_id").is(comment1.getId()));
        Update update = new Update();
        update.inc("likeCount", 1);
        FindAndModifyOptions modify = new FindAndModifyOptions();
        modify.returnNew(true);
        Comment andModify = mongoTemplate.findAndModify(query, update, modify, comment.getClass());
        //往redis存入hashkey

        Map<String, Comment> map = new HashMap<>();
        map.put("comment", comment);
        map.put("andModify", andModify);
        return map;
    }

/*    @Override
    public Boolean dislikeCount(Comment comment) {
        return null;
    }*/

    @Override
    public Map<String, Comment> commentsdislike(Comment comment) {
        //找到comment表里面的 评论点赞的文档，随后删除
        //查询到点赞数据
        Query query1 = Query.query(Criteria.where("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType())
                .and("userId").is(comment.getUserId()));
        //删除comment表里面的点赞记录
        Comment andRemove = mongoTemplate.findAndRemove(query1, Comment.class);

        //更新comment表，评论点赞数据-1
        Query query = new Query(Criteria.where("_id").is(comment.getPublishId()));
        Update update = new Update();
        update.inc("likeCount", -1);
        FindAndModifyOptions modify = new FindAndModifyOptions();
        modify.returnNew(true);
        Comment andModify = mongoTemplate.findAndModify(query, update, modify, comment.getClass());

        Map<String, Comment> map = new HashMap<>();
        map.put("comment", andRemove);
        map.put("andModify", andModify);


        return map;
    }

    //依据PublisUserId 找到被点赞的数据
    @Override
    public List<Comment> findPublisUserId(Long publishUserId, Integer page, Integer pagesize,int commentType) {
        Query query = Query.query(Criteria.where("publishUserId").is(publishUserId)
                                  .and("commentType").is(commentType))
                .skip((page - 1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments;
    }


}
